package com.wh.message.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.Map.Entry;


/**
 * post请求工具
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.voice.service
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class HttpPostUtil {


	/**
	 *
	 * @param url
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public String httpPost(String url, Map<String, Object> map) throws Exception {
		return httpPost(url, map, null);
	}

	/**
	 * post请求
	 * @param url    请求地址
	 * @param body 	 要post的数据
	 * @return
	 * @throws IOException
	 */
	public String post(String url, Map<String, String> headers, String body) throws Exception{
		String result = "";
		try
		{
			OutputStreamWriter out = null;
			BufferedReader in = null;
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			// 添加请求头
			Set<String> keys = headers.keySet();
			for (String key : keys) {
				conn.setRequestProperty(key, headers.get(key));
			}

			//设置连接参数
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setConnectTimeout(4000);
			conn.setReadTimeout(5000);

			// 提交数据
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF8");
			out.write(body);
			out.flush();

			// 读取返回数据
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF8"));
			String line = "";
			while ((line = in.readLine()) != null)
			{
				result += "\n";
				result += line;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}

	public String httpPost(String url, Map<String, Object> map,  Map<String, String> headers) throws Exception {
		// 设置参数
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		if (null != map) {
			Iterator iterator = map.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
		}
		CloseableHttpClient httpClient = getHttpClient();
		try {
			HttpPost post = new HttpPost(url);
			if (null != headers) {
				// post.setHeader("Content-Type", "application/json");
				if (headers != null) {
					Set<String> keys = headers.keySet();
					for (Iterator<String> i = keys.iterator(); i.hasNext();) {
						String key = (String) i.next();
						post.addHeader(key, headers.get(key));

					}
				}
			}

			// url格式编码
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
			post.setEntity(uefEntity);
			// 执行请求
			CloseableHttpResponse httpResponse = httpClient.execute(post);
			try {
				HttpEntity entity = httpResponse.getEntity();
				if (null != entity) {
					// 原始数据
					return EntityUtils.toString(entity);
				}
			} finally {
				httpResponse.close();
			}
		} catch (UnsupportedEncodingException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				closeHttpClient(httpClient);
			} catch (Exception e) {
				throw e;
			}
		}
		return null;
	}

	private CloseableHttpClient getHttpClient() {
		return HttpClients.createDefault();
	}

	private void closeHttpClient(CloseableHttpClient client) throws IOException {
		if (client != null) {
			client.close();
		}
	}
}
